package com.sdk.ks;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coment.dto.ApiNotify;
import com.coment.dto.LiveData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdk.config.TokenConfig;
import com.sdk.constant.ConstantKuaiShou;
import com.sdk.utill.HttpUtil;
import com.sdk.utill.KSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class KSServiceImpl {
    private final ObjectMapper objectMapper = new ObjectMapper();

    public List<ApiNotify> parseKuaishou(String jsonStr) {
//      log.info("请求体：{}", jsonStr);
        LiveData.KSPayload ksPayload = JSONObject.parseObject(jsonStr, LiveData.KSPayload.class);
        return ApiNotify.toApiNotifyList(ksPayload);
    }

    private Map<String, String> createJsonHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json;charset=UTF-8");
        return headers;
    }

    private Map<String, String> createFormHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/x-www-form-urlencoded");
        return headers;
    }

    public KSResponse bind(
            String roomCode,
            String actionType
    ) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        log.info("roomCode：{}", roomCode);
        Map<String, Object> bind = KSUtil.createRequest(roomCode, actionType, "bind", null, data);
        String url = ConstantKuaiShou.POST_BIND_NOTIFY + "?app_id=" + KSConfig.appId + "&access_token=" +  TokenConfig.ks_token ;
        String response = HttpUtil.sendPost(url, JSON.toJSONString(bind), this.createJsonHeaders());
        log.info("URL：{},请求体：{}，响应体：{}", url, bind, response);
        return this.objectMapper.readValue(response, KSResponse.class);
    }

    public KSResponse toTop(String roomCode) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        data.put("giftList", KSConfig.gift_ids);
        data.put("giftExtendInfo", "");
        Map<String, Object> top = KSUtil.createRequest(roomCode, KsActionType.top.getValue(), "gift", null, data);
        String response = HttpUtil.sendPost(ConstantKuaiShou.POST_GIFT_TOP + "?app_id=" + KSConfig.appId + "&access_token=" + TokenConfig.ks_token, JSON.toJSONString(top), this.createJsonHeaders());
        return this.objectMapper.readValue(response, KSResponse.class);
    }

    public KSResponse getAccessToken() throws JsonProcessingException {
        String response = HttpUtil.sendGet(ConstantKuaiShou.GET_ACCESS_TOKEN, this.createFormHeaders());
        log.info("URL：{}，响应体：{}", ConstantKuaiShou.GET_ACCESS_TOKEN, response);
        return this.objectMapper.readValue(response, KSResponse.class);
    }

    public KSResponse geQueryFieldList(String roomCode, String pushType) throws JsonProcessingException {
        Map<String, Object> request = KSUtil.createRequest(roomCode, null, null, pushType, null);
        log.info("URL：{}，请求体：{}", ConstantKuaiShou.POST_QUERY, request);
        String postStr = HttpUtil.sendPost(ConstantKuaiShou.POST_QUERY, JSON.toJSONString(request), this.createJsonHeaders());
        return this.objectMapper.readValue(postStr, KSResponse.class);
    }

    @Value("${spring.application.env}")
    public String env;

    /// 24 小时刷新一次access_token
    @Scheduled(fixedRate = 24, timeUnit = TimeUnit.HOURS)
    public void refreshAccessToken() {
        if (!env.equals("dev")) {
            try {
                KSResponse accessToken = this.getAccessToken();
                if (accessToken.getResult() == 1) {
                    log.info("刷新access_token成功");
                    TokenConfig.ks_token = accessToken.getAccessToken();
                }else {
                    log.error("刷新access_token失败");
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
